layui.define(['element', 'api', 'fast_config','object_design','utils','form'], function(exports) {
    "use strict";

    /**
     * Button component
     * */
    var MOD_NAME = 'fact_design',
        $ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        object_design = layui.object_design,
        form = layui.form,
        utils = layui.utils,
        rowIndex
    ;

    var fact_design = function(opt) {
        this.option = opt;
    };

    var initFieldDate = function(option) {
        option.fields = {};
        api.exec({
            enableRootPath:true,
            type: "GET",
            url: fast_config.moudle.brms.modelsApi.format(option.treeData),
            success: function(data){
                let arr=[];
                for(let i=0;i<data.length;i++){
                    let model={};
                    model['code'] = data[i].id;
                    model['name'] = data[i].name;

                    arr.push(model);
                }
                option.fields['array'] = arr;
            }
        });

    }

    /**
     * Button start loading
     * */
    fact_design.prototype.render = function(opt) {

        var option = {
            elem: opt.elem,
            initData:opt.initData,
            treeData: opt.treeData,
            grid: null
        }

        initFieldDate(option);

        var grid;
        // var parentContextData = window.parent.window.contextData;
        // var path = parentContextData.contextmenuData.data.path;
        var metaName;

        //called when save changes button is clicked.
        function saveChanges() {

            //attempt to save editing cell.
            if (grid.saveEditCell() === false) {
                return false;
            }

            if ( grid.isDirty() && grid.isValidChange({ focusInvalid: true }).valid ) {

                var changes = grid.getChanges({ format: "byVal" });

                //post changes to server
                api.post({
                    enableRootPath: true,
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        grid.showLoading();
                    },
                    url: "/meta/" + metaName + "/batch",
                    // contextT
                    data: JSON.stringify(changes),
                    headers:{'Content-Type':'application/json;charset=utf8'},
                    success: function (changes) {
                        grid.commit({ type: 'add', rows: changes.addList });
                        grid.commit({ type: 'update', rows: changes.updateList });
                        grid.commit({ type: 'delete', rows: changes.deleteList });

                        grid.history({ method: 'reset' });
                    },
                    complete: function () {
                        grid.hideLoading();
                    }
                });
            }
        }

        var types = [
            {"id":"basic","value":"basic","name": "基础类型"},
            {"id":"dd","value":"dd", "name": "数据字典"},
            {"id":"mdm","value":"mdm", "name": "基础数据"},
            {"id":"object","value":"object", "name": "对象"},
            {"id":"array","value":"array", "name": "集合"}
        ];

        var data=[];
        if(option.initData){
            data = option.initData;
            for(var field of data){
                field.pq_rowselect = undefined;
                field.state = false
            }
        }

        function getFieldClass(type){
            if(type ==='object' || type ==='array'){
                type='array';
            } else if(!option.fields[type]){
                api.exec({
                    enableRootPath:true,
                    type: "GET",
                    url: fast_config.moudle.domain.fieldClassApi.format({type:type}),
                    success: function(data){
                        option.fields[type] = data;
                    }
                });
            }

            return option.fields[type];
        }

        var fieldClass = function (ui){
            let type=ui.rowData.fieldType;
            if(type==''){
                type = "basic";
            }
            return getFieldClass(type);
        }

        grid = object_design.render({
            elem: option.elem,
            initData:data,
            grid: null,
            gridSetting:{
                colModel: [
                    { dataIndx: "state", maxWidth: 30, minWidth: 30, align: "center", resizable: false,
                        type: 'checkBoxSelection', cls: 'ui-state-default', sortable: false, editor: false,
                        dataType: 'bool',
                        cb: {
                            all: true,
                            header: true,
                            select: true
                        }
                    },
                    { title: "名称", dataType: "string", dataIndx: "fieldComment",
                        validations: [{ type: 'minLen', value: "1", msg: "必填"}]
                    },
                    { title: "英文名", dataType: "string", dataIndx: "fieldName",
                        validations: [{ type: 'minLen', value: "1", msg: "必填"}]
                    },
                    { title: "类别", dataIndx: "fieldType",
                        editor: {
                            type: "select",
                            labelIndx: "name",
                            valueIndx: "id",
                            prepend: { "": "" },
                            options: types
                        },
                        // validations: [{ type: 'minLen', value: "1", msg: "必填"}],
                        render : function (ui) {
                            var rowData = ui.rowData,
                                dataIndx = ui.dataIndx;

                            rowData.pq_cellcls = rowData.pq_cellcls || {};

                            let name = null;
                            $.each(types,function(index,obj){
                                if(rowData[dataIndx] == obj.id){
                                    name = obj.name
                                    return true;
                                }
                            });
                            return name;
                        }
                    },
                    { title: "字段类型", dataIndx: "fieldClass",
                        editor: {
                            type: "select",
                            labelIndx: "name",
                            valueIndx: "code",
                            prepend: { "": "" },
                            options: fieldClass
                        },
                        // validations: [{ type: 'minLen', value: "1", msg: "必填"}],
                        render : function (ui) {
                            var rowData = ui.rowData,
                                dataIndx = ui.dataIndx;

                            rowData.pq_cellcls = rowData.pq_cellcls || {};

                            let type=ui.rowData.fieldType;
                            if(type==''){
                                type = "basic";
                            }
                            let fcls = getFieldClass(type)

                            let name = null;
                            $.each(fcls,function(index,obj){
                                if(rowData[dataIndx] == obj.code){
                                    name = obj.name
                                    return true;
                                }
                            });
                            return name;
                        }
                    }
                ],
                defaultRowData:{ fieldComment: "字段", fieldName: "field", fieldType: "basic", fieldClass: "String"}
            }
        });

        option.grid = grid.option.grid;

        return new fact_design(option);
    }

    exports(MOD_NAME, new fact_design());
});
